package com.littrabble.string;

public class StringTest {

	public static void main(String[] args) {
		String source = "This except exception will be thrown by the FileInputStream FileOutputStream"
				+ " and RandomAccessFile constructors when a file with the specified pathname does not"
				+ " exist It will also be thrown by these constructors if the file does exist but for"
				+ " some reason is inaccessible for example when an attempt is made to open a read-only file for writing";

		String target = "exception";

		int index = indexOf(source, target);
	}

	public static int indexOf(String source, String target) {

		char[] s = source.toCharArray();
		char[] t = target.toCharArray();

		return indexOf(s, s.length, t, t.length);
	}

	public static int indexOf(char[] source, int sourceCount, char[] target,
			int targetCount) {

		char first = target[0];
		int max = sourceCount - targetCount;

		for (int i = 0; i <= max; i++) {
			if (source[i] != first) {
				while (++i <= max && source[i] != first)
					;
			}

			if (i <= max) {
				int j = i + 1;
				int end = i + targetCount - 1;

				for (int k = 1; j <= end && source[j] == target[k]; j++, k++);

				if (j - 1 == end) {
					return i;
				}
			}
		}

		return -1;
	}
}
